#include "Modify.h"
#include "ui_Modify.h"
#include <QMessageBox>
#include <QBitmap>
#include <QStyleOption>
#include <QPainter>
#include <QMouseEvent>
#include "mymessagebox.h"

Modify::Modify(const QString &id, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Modify)
    , employeeId(id)  // 通过构造函数传递工号
    , tcpSocket(new QTcpSocket(this))  // 创建TCP套接字
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    ui->past->setEchoMode(QLineEdit::Password);
    ui->now->setEchoMode(QLineEdit::Password);

    // 连接到服务器
    tcpSocket->connectToHost("127.0.0.1", 12348);

    // 设置信号槽连接，监听服务器响应
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Modify::readFromServer);
}

Modify::~Modify()
{
    delete ui;
}

// 实现窗口拖动功能
void Modify::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 50) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Modify::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Modify::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 20, 20); // 在 bitmap 中绘制圆角矩形

    // 手动绘制边框
    QPainter borderPainter(this);
    borderPainter.setRenderHint(QPainter::Antialiasing);
    QPen pen(QColor("#55aaff")); // 设置边框颜色
    pen.setWidth(2);              // 设置边框宽度
    borderPainter.setPen(pen);
    borderPainter.setBrush(Qt::NoBrush);
    QRect rect = this->rect();
    rect.adjust(1, 1, -1, -1); // 调整边框矩形，以确保边框在控件内部
    borderPainter.drawRoundedRect(rect, 20, 20); // 绘制圆角边框

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Modify::on_returnButton_clicked()
{
    this->close();
}

void Modify::on_yes_clicked()
{
    // 获取原密码和新密码
    QString oldPassword = ui->past->text();
    QString newPassword = ui->now->text();

    // 判断密码是否为空
    if (oldPassword.isEmpty() || newPassword.isEmpty()) {
        // QMessageBox::warning(this, "输入错误", "请输入原密码和新密码！");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("输入错误");
        msgBox.setText("请输入原密码和新密码！");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 发送修改密码请求到服务器
    sendPasswordChangeRequest(oldPassword, newPassword);
}

void Modify::sendPasswordChangeRequest(const QString &oldPassword, const QString &newPassword)
{
    if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        QString request = QString("CHANGE_PASSWORD|%1|%2|%3")
        .arg(employeeId)
            .arg(oldPassword)
            .arg(newPassword);
        tcpSocket->write(request.toUtf8());
    } else {
        // QMessageBox::warning(this, "连接失败", "无法连接到服务器");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("连接失败");
        msgBox.setText("无法连接到服务器");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

void Modify::readFromServer()
{
    QByteArray data = tcpSocket->readAll();
    QString response = QString::fromUtf8(data);

    if (response == "PASSWORD_MISMATCH") {
        // QMessageBox::warning(this, "错误", "原密码错误！");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("原密码错误！");
        msgBox.setButton("确定");
        msgBox.exec();
    } else if (response == "PASSWORD_CHANGED") {
        // QMessageBox::information(this, "成功", "密码修改成功！");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("成功");
        msgBox.setText("密码修改成功！");
        msgBox.setButton("确定");
        msgBox.exec();

        // 清空输入框
        ui->past->clear();
        ui->now->clear();
    }
}

void Modify::on_no_clicked()
{
    this->close();
}

